<?php

namespace App\Http\Middleware;

use App\Exceptions\ExceptionHelper;
use App\Http\Request;
use Closure;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ApiRequest
{
    /**
     * 接口签名中间件.
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->wantsJson()) {
            throw new NotFoundHttpException();
        }
        if (is_production()) {
//            $sign      = Request::getSign();
//            $timestamp = Request::getTimestamp();
//
//            if (abs(time() - $timestamp) > 300) {
//                \Log::info("无效的请求:" . $timestamp . "; " . time());
//                throw ExceptionHelper::getInstance(ExceptionHelper::INVALID_REQUEST);
//            }
//
//            if ($request->isMethod(Request::GET_METHOD)) {
//                $requestContent = $request->getQueryString() ?? '';
//            } else {
//                $requestContent = $request->post();
//                $requestContent = $this->buildQuery($requestContent);
//            }
//            $requestContent = $requestContent . ($requestContent ? '&' : '') . 'secret=' . config('common.api_secret') . '&timestamp=' . $timestamp;
//            $requestSign = md5(urldecode($requestContent));
//            if ($requestSign != $sign) {
//                throw ExceptionHelper::getInstance(ExceptionHelper::SIGN_ERROR);
//            }
        }
        return $next($request);
    }

    private function buildQuery($params)
    {
        ksort($params);
        $str = '';
        foreach ($params as $k => $v) {
            $str .= sprintf("&%s=%s", $k, $v);
        }
        return substr($str, 1);
    }
}
